from django import forms
from basedata.models import City, Feature

__author__ = 'mayufeng'


class SearchForm(forms.Form):
    name = forms.CharField(required=False)
    city_name = forms.CharField(required=False)


class AreaForm(forms.ModelForm):
    state_name = forms.CharField(required=False, label='州名称')
    city_name = forms.CharField(required=False, label='城市名称')
    category = forms.CharField(required=True, label='级别')

    class Meta:
        model = City
        fields = ['city_name', 'city_code', 'state_name', 'state_code', 'area_name', 'category', 'parent']

    def clean(self):
        cleaned_data = super(AreaForm, self).clean()
        state_name = cleaned_data.get("state_name")
        city_name = cleaned_data.get("city_name")
        area_name = cleaned_data.get("area_name")
        category = cleaned_data.get("category")
        return cleaned_data

    def save(self, commit=True):
        city = super(AreaForm, self).save(commit)
        if self.cleaned_data['category'] == 'S':
            city.state_name = self.cleaned_data['state_name']
        elif self.cleaned_data['category'] == 'C':
            city.parent_id = self.cleaned_data['state_name']
            city.city_name = self.cleaned_data['city_name']
        else:
            city.parent_id = self.cleaned_data['city_name']
        city.save()
        return city



class FeatureForm(forms.ModelForm):
    class Meta:
        model = Feature
        fields = ['name']
